﻿using blackhouse.AsyncMail.Business;
using blackhouse.AsyncMail.Business.Data;
using Quartz;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;

namespace blackhouse.AsyncMail.Web {
    public class SendMailJob :IJob {

        public void Execute(IJobExecutionContext context) {
            this.RunTask(context.JobDetail.JobDataMap.GetString("host"));
        }

        private void RunTask(string host) {
            ASyncMail mail = new ASyncMail(new SqlASyncMailDataAccess(CacheTaskRunner.GetConnectionString()));
            while (mail.FillByTop()) {
                try {
                    SendMail(mail, host);
                    mail.MarkAsSended();
                }
                catch (Exception e) {
                    mail.MarkSendError(e.Message + "\r\n" + e.StackTrace);
                }
            }
        }

        private static void SendMail(ASyncMail mail, string host) {
            string url = host + "/" + ASyncHtmlMailGenerator.GetMailDirectory() + "/ASyncHtmlMailGenerator.aspx?requestId=" + mail.RequestId;
            WebRequest request = HttpWebRequest.Create(url);
            WebResponse response = request.GetResponse();
            string mailToSend = "";
            using (Stream stream = response.GetResponseStream())
            using (StreamReader sr = new StreamReader(stream)) {
                mailToSend = sr.ReadToEnd();
            }
            MailMessage mailMessage = new MailMessage();
            SmtpClient client = new SmtpClient();
            if (client.Port == 587)
                client.EnableSsl = true;
            mailMessage.Subject = mail.MessageTitle;
            mailMessage.Body = mailToSend;
            mailMessage.IsBodyHtml = true;
            mailMessage.To.Add(mail.GetReceiver());
            client.Send(mailMessage);
        }

    }
}